package com.rmt.www.daoImpl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.rmt.www.dao.TraceabilityDao;
import com.rmt.www.vo.Traceability;

public class TraceabilityDaoImpl implements TraceabilityDao {

	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public void deleteTraceabilityByTId(int tid) {
		this.jdbcTemplate.update("delete from traceability where tid=?", 
				new Object[]{tid}, new int[]{java.sql.Types.INTEGER});
	}

	@SuppressWarnings("unchecked")
	public List<Traceability> getTraceabilitiesByFromId(int artifactfromid) {
		return this.jdbcTemplate.query("select * from traceability where artifactfromid=?", 
				new Object[]{artifactfromid}, new int[]{java.sql.Types.INTEGER}, new TraceabilityRowMapper());
	}

	@SuppressWarnings("unchecked")
	public List<Traceability> getTraceabilitiesByToId(int artifacttoid) {
		return this.jdbcTemplate.query("select * from traceability where artifacttoid=?", 
				new Object[]{artifacttoid}, new int[]{java.sql.Types.INTEGER}, new TraceabilityRowMapper());
	}

	public void insertTraceability(Traceability newTraceability) {
		this.jdbcTemplate.update("insert into traceability(artifactfromid, artifacttoid) values(?, ?)",
				new Object[]{newTraceability.getArtifactfromid(), newTraceability.getArtifacttoid()},
				new int[]{java.sql.Types.INTEGER,java.sql.Types.INTEGER});
	}

	public void updateTraceability(Traceability newTraceability) {
		this.jdbcTemplate.update("update traceability set artifactfromid=?, artifacttoid=? where tid=?",
				new Object[]{newTraceability.getArtifactfromid(), newTraceability.getArtifacttoid(), newTraceability.getTid()},
				new int[]{java.sql.Types.INTEGER,java.sql.Types.INTEGER,java.sql.Types.INTEGER});
	}

	public boolean determinDependencyByFromAndToId(int fromId, int toId) {
		try{
			Object t= this.jdbcTemplate.queryForObject("select * from traceability where artifactfromid=? and artifacttoid=?", new Object[]{fromId, toId}, new int[]{java.sql.Types.INTEGER,java.sql.Types.INTEGER}, new TraceabilityRowMapper());
			return true;
		}
		catch(Exception e){
			return false;
		}
		
	}

	public void deleteTraceabilityByFromIdAndToId(int fromId, int toId) {
		this.jdbcTemplate.update("delete from traceability where artifactfromid=? and artifacttoid=?", 
				new Object[]{fromId,toId}, new int[]{java.sql.Types.INTEGER,java.sql.Types.INTEGER});
		
	}

}
